<?php

namespace App\Admin\Controllers\Auth;

use App\Admin\Traits\RouteHelper;
use App\Admin\Services\GrantService;
use App\Admin\Controllers\Controller;
use App\Admin\Requests\PermissionStoreRequest;
use App\Admin\Requests\PermissionUpdateRequest;
use App\Models\Permission;

class PermissionController extends Controller
{
    use RouteHelper;

    protected $grantService;

    public function __construct(GrantService $grantService)
    {
        parent::__construct();
        $this->grantService = $grantService;
    }

    /**
     * 權限列表
     */
    public function index()
    {
        //獲取所有權限提供前台選擇
        if (request()->expectsJson()) {
            $paginate = Permission::query()
                ->when(request('keyword'), function ($query) {
                    $query->where('name', 'like', '%' . request('keyword') . '%');
                })
                ->paginate(request('limit', 30));

            return $this->laytable($paginate->total(), $paginate->items());
        }

        return view('admin.permission.index');
    }

    /**
     * 添加權限-前台
     */
    public function create()
    {
        //獲取所有權限提供前台選擇
        $all_routes    = $this->getRoutes();
        $format_routes = [];

        foreach ($all_routes as $route) {
            $description                      = explode(":", $route['description']);
            $route['description']             = $description[1] ?? $description[0];
            $format_routes[$description[0]][] = $route;
        }

        return view('admin.permission.create', [
            'format_routes' => $format_routes,
        ]);
    }

    /**
     * 添加權限-後台
     */
    public function store(PermissionStoreRequest $request)
    {
        $name       = request('name');
        $permission = request('permissions', []);

        try {
            if ($this->grantService->createPermission($name, implode(",", $permission))) {
                return $this->success('操作成功', [], 200, broute('permission.index'));
            }
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }

        return $this->failure('操作失敗');
    }

    public function edit()
    {
        $id            = request()->id;
        $info          = $this->grantService->getPermissionIn($id);
        $routes        = explode(',', $info->route);
        $all_routes    = $this->getRoutes();
        $format_routes = [];

        foreach ($all_routes as $route) {
            $description                      = explode(":", $route['description']);
            $route['description']             = $description[1] ?? $description[0];
            $format_routes[$description[0]][] = $route;
        }

        return view('admin.permission.edit', [
            'info'          => $info,
            'routes'        => $this->getRoutes(),
            'ownRoutes'     => $routes,
            'format_routes' => $format_routes,
        ]);
    }

    public function update(PermissionUpdateRequest $request)
    {
        $id          = request('id');
        $name        = request('name');
        $permissions = request('permissions', []);

        try {
            if ($this->grantService->syncPermission($id, $name, implode(",", $permissions))) {
                return $this->success('操作成功', [], 200, broute('permission.index'));
            }
        } catch (\Exception $e) {
            // return $this->failure('權限更新一次,請檢查權限名稱是否衝突!');
            return $this->failure($e->getMessage());
        }

        return $this->failure('操作失敗');
    }

    /**
     * 刪除權限
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function delete()
    {
        $id = request('id');

        if (empty($id)) {
            return $this->failure('未選擇', [], 200, '');
        }

        try {
            if ($this->grantService->deletePermissions($id)) {
                return $this->success('刪除成功');
            }
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }

        return $this->failure('刪除失敗');
    }

}
